<template>
  <Dialog v-model="dialogVisible" title="线索导入" width="400">
    <el-upload
      ref="uploadRef"
      v-model:file-list="fileList"
      :action="importUrl"
      :auto-upload="false"
      :disabled="formLoading"
      :headers="uploadHeaders"
      :limit="1"
      :on-error="submitFormError"
      :on-exceed="handleExceed"
      :on-success="submitFormSuccess"
      :data="{ isUpdateSupport: updateSupport }"
      accept=".xlsx, .xls"
      drag
    >
      <Icon icon="ep:upload" />
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="updateSupport" />
            是否更新已经存在的线索数据
          </div>
          <span>仅允许导入 xls、xlsx 格式文件。</span>
          <el-link
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            type="primary"
            @click="importTemplate"
          >
            下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as LeadsApi from '@/api/weiyi/leads'
import { getAccessToken, getTenantId } from '@/utils/auth'
import download from '@/utils/download'

defineOptions({ name: 'LeadsImportForm' })

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中
const uploadRef = ref()
const importUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/weiyi/leads/import'
const uploadHeaders = ref() // 上传 Header 头
const fileList = ref([]) // 文件列表
const updateSupport = ref(false) // 是否更新已经存在的线索数据

/** 打开弹窗 */
const open = async () => {
  dialogVisible.value = true
  // 设置上传 Header 头
  uploadHeaders.value = {
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 下载模板操作 */
const importTemplate = async () => {
  try {
    const data = await LeadsApi.LeadsApi.getImportTemplate()
    download.excel(data, '线索导入模板.xlsx')
  } catch (error) {
    console.error('下载模板失败:', error)
  }
}

/** 上传错误 */
const submitFormError = (error: any) => {
  message.error('导入失败：' + error.message)
  formLoading.value = false
}

/** 上传成功 */
const submitFormSuccess = (response: any) => {
  formLoading.value = false
  const { code, data, msg } = response
  if (code === 0) {
    dialogVisible.value = false
    fileList.value = []
    
    // 构建结果提示信息
    let resultMsg = [
      `导入结果：`,
      `新增成功：${data.createCount} 条`,
      `更新成功：${data.updateCount} 条`,
      `失败数量：${data.failureCount} 条`
    ]

    // 如果有失败记录，添加失败详情
    if (data.failures && data.failures.length > 0) {
      resultMsg.push('\n失败详情：')
      data.failures.forEach((failure: any) => {
        resultMsg.push(`第 ${failure.rowIndex} 行：${failure.field} - ${failure.reason}`)
      })
    }

    // 使用 pre 标签包裹内容，保持换行格式
    const htmlContent = `<pre style="margin: 0; white-space: pre-wrap; font-family: inherit;">${resultMsg.join('\n')}</pre>`

    // 使用 alert 展示完整的导入结果
    message.alert(htmlContent, '导入完成', {
      type: data.failureCount > 0 ? 'warning' : 'success',
      dangerouslyUseHTMLString: true,
      customClass: 'import-result-dialog'
    })

    emit('success')
  } else {
    message.error(msg)
  }
}

/** 提交上传文件 */
const submitForm = async () => {
  const uploadFile = fileList.value[0]
  if (!uploadFile) {
    message.error('请选择需要上传的文件!')
    return
  }
  formLoading.value = true
  uploadRef.value!.submit()
}

/** 上传文件超出限制 */
const handleExceed = () => {
  message.error('最多只能上传一个文件!')
}

/** 定义 success 事件，用于操作成功后的回调 */
const emit = defineEmits(['success'])
</script> 